<template>
    <div class="wrapper">
        <!--header部分-->
        <header>
            <p>确认订单</p>
        </header>
        <page-rollback></page-rollback>

        <!--订单客户信息部分-->
        <div class="order-info">
            <h5>订单配送至：</h5>
            <div class="order-info-address" @click="toUserAddress">
                <p>{{deliveryaddress!=null?deliveryaddress.address:'请选择送货地址'}}</p>
                <!--右箭头-->
                <i class="fa fa-angle-right"></i>
            </div>
            <h5>{{user.userName}}{{sexFilter(user.userSex)}} {{maskedPhoneNumber}}</h5>
        </div>

        <!--订单商家信息部分-->
        <h3>{{business.businessName}}</h3>

        <!--订单明细部分-->
        <ul class="order-detailed">
            <!--采用无序列表-->
            <li v-for="item in cartArr" :key="item.id">
                <div class="order-detailed-left">
                    <img :src = "item.food.foodImg" >
                    <p>{{item.food.foodName}} x {{item.quantity}}</p>
                </div>
                <!--利用转义符表示¥-->
                <p>{{this.$formatMoney(item.food.foodPrice*item.quantity, '￥')}}</p> 
            </li>
        </ul>
        <div class="order-deliveryfree">
            <p>配送费</p>
            <p>{{this.$formatMoney(business.deliveryPrice, '￥')}}</p>
        </div>

        <!--订单优惠部分-->
        <div class="discount">
            <div class="discount-member" v-show="user.member">
                <div class="discount-member-left">
                    <i class="fa fa-user-o"></i>
                    <p>会员折扣</p>
                </div>
                <div class="discount-member-right">
                    <p>-{{this.$formatMoney( memberCutPrice, '￥')}}</p>
                </div>
            </div>
            <div class="discount-coupon-package">
                <div class="discount-coupon-package-left">
                    <p>券</p>
                    <p>我的券包</p>
                </div>
                <div class="discount-coupon-package-right">
                    <div class="discount-coupon-package-right-used" v-if="isCouponUsed">
                        <p>-{{this.$formatMoney(couponUsedAmount, '￥')}}</p>
                    </div>
                    <div class="discount-coupon-package-right-unused" v-else>
                        <p>{{ couponNumber }}张可用</p>
                        <!--右箭头-->
                        <i class="fa fa-angle-right" @click="toUserCouponPackage"></i>
                    </div>
                </div>     
            </div>
            <div class="discount-score">
                <div class="discount-score-left">
                    <div class="discount-score-left-icon">&#165;</div>
                    <p>是否选择积分抵用</p>
                </div>
                <div class="discount-score-right">
                    <div class="discount-score-right-userOrNot" style="font-size: 4vw;"> 
					<!--radio表示一组中单选，name相同的为一组，checked 表示默认-->
                        <input type="radio"  name = 'userOrNot'  v-model="userOrNot" value="1" style="width:6vw;height: 4vw;" @change="handleUserOrNotSelection(1)"> 是
                        <input type="radio"  name = 'userOrNot'  v-model="userOrNot" value="0" style="width:6vw;height: 4vw;" @change="handleUserOrNotSelection(0)"> 否
                    </div>
                    <p>-{{this.$formatMoney(scoreCutPrice, '￥')}}</p>
                </div> 
            </div>
        </div>
        <!--订单合计部分-->
        <div class="total">
            <div class="total-left">
                <p>{{this.$formatMoney(totalPrice-totalCut, '￥')}}</p>
                <p>已优惠{{this.$formatMoney( totalCut, '￥')}}</p>
            </div>
            <div class="total-right" @click="toPayment">
                去支付
            </div>
        </div>
    </div>
</template>

<script>
import PageRollback from '@/components/PageRollback.vue';

export default{
    name:'OrderPage',
    data(){
        return{
            businessId:this.$route.query.businessId ,
            business: {},
            user: {},
            cartArr: [],
            deliveryaddress: {},
            pointArr:[],
            coupon_10_2:'',
            coupon_20_3:'',
            coupon_30_5:'',
            coupon_20_6:'',
            coupon_30_10:'',
            coupon_50_15:'',
            userOrNot:'',
            isCouponUsed: this.$route.query.isCouponUsed ,
            showCouponUseBottom: true,
            couponUsedAmount:this.$route.query.couponUsedAmount ,
            usedCouponPackage:  this.$route.query.usedCouponPackage
        }
    },
    created(){
        this.user = this.$getSessionStorage('user');
        this.deliveryaddress = this.$getLocalStorage(this.user.userId);
        
        let url_getBusiness = `/BusinessController/getBusinessById/${this.businessId}`;
        //查询当前商家
        this.$axios.get(url_getBusiness)
        .then(response=>{
            this.business = response.data.result;
        })
        .catch(error=>{
            console.error(error);
        });

        let url_getCart = `/CartController/listCart/${this.user.token.token}/${this.businessId}`;
        //查询当前用户在购物车中的当前商家食品列表
        this.$axios.get(url_getCart)
        .then(response=>{
            this.cartArr = response.data.result;
        })
        .catch(error=>{
            console.error(error);
        });

        // 查询当前用户的优惠券信息
        let url_getCoupon = `/CouponController/getCouponById/${this.user.token.token}`;
        this.$axios.get(url_getCoupon)
        .then(response => {
            console.log(response.data.result);
            this.coupon_10_2= response.data.result.coupon_10_2;
            this.coupon_20_3= response.data.result.coupon_20_3;
            this.coupon_30_5= response.data.result.coupon_30_5;
            this.coupon_20_6= response.data.result.coupon_20_6;
            this.coupon_30_10= response.data.result.coupon_30_10;
            this.coupon_50_15= response.data.result.coupon_50_15;
        })
        .catch(error => {
            console.error(error);
        });

        let url_getPoint = `/PointController/checkPoints/${this.user.token.token}`
        //获取用户的积分信息
        this.$axios.get(url_getPoint)
			.then(response => {
				this.pointArr = response.data.result;
			}).
			catch(error => {
				console.error(error);
			});

    },  
    computed: {
        totalPrice(){
            let totalPrice = 0;
            for(let cartItem of this.cartArr){
                totalPrice += cartItem.food.foodPrice*cartItem.quantity;
            }
            totalPrice += this.business.deliveryPrice;
            return totalPrice;
        },
        memberCutPrice(){
            return this.totalPrice * 0.05;
        },
        scoreCutPrice(){
            let totalScore = 0;
            for(let i = 0; i < this.pointArr.length ; i++){
                    let point = this.pointArr[i];
                    totalScore += point.points;
            }
            return totalScore * 0.01;
        },
        totalUsedScore(){
            let totalScore = 0;
            if(this.userOrNot === 1){
                for(let i = 0; i < this.pointArr.length ; i++){
                    let point = this.pointArr[i];
                    totalScore += point.points;
                }
            }
            return totalScore; 
        },
        totalCut(){
            let total = 0;
            if(this.user.member){
                total += this.memberCutPrice;
            }
            if(this.userOrNot === 1){
                total += this.scoreCutPrice;
            }
            if(this.isCouponUsed){
                total += this.couponUsedAmount*1;
            }
            return total ;
        },
        maskedPhoneNumber() {
            return this.user.userId.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
        },
        couponNumber(){
            return this.coupon_10_2+ this.coupon_20_3 + this.coupon_20_6
            + this.coupon_30_10 + this.coupon_30_5 + this.coupon_50_15;
        }
    },
    // vue3过滤器已经弃用了，需要改写为method里面自定义的过滤器
    //filters: {
    //    sexFilter(value){
    //    return value==1?'先生':'女士';
    //    }
    //},
    methods: {
        toUserAddress(){
            this.$router.push({path:'/userAddress',query:{businessId: this.businessId}});
        },
        toPayment(){
            if(this.deliveryaddress === null){
                alert('请选择收货地址！');
                return;
            }
            let url_createOrders = `/OrdersController/createOrders/${this.user.token.token}/${this.businessId}/${this.deliveryaddress.daId}/${this.totalPrice - this.totalCut}/${this.isCouponUsed? this.usedCouponPackage: '0'}/${this.totalUsedScore}`;
            //创建订单
            this.$axios.post(url_createOrders)
            //     `OrdersController/createOrders/${this.user.token.token}`, this.$qs.stringify({
            //     //userId:this.user.userId,
            //     businessId:this.businessId,
            //     daId:this.deliveryaddress.daId,
            //     orderTotal:this.totalPrice - this.totalCut,
            //     coupon: this.isCouponUsed? this.usedCouponPackage: '',
            //     points: this.totalUsedScore
            // }))
            .then(response =>{
                let orderId = response.data.result;
                if(orderId > 0){
                    this.$router.push({path:'/payment', query:{orderId: orderId}});
                }else{
                    alert('创建订单失败！');
                }
            })
            .catch(error => {
                console.error(error);
            });

            // this.$axios.post('OrdersController/updateOrders', this.$qs.stringify({
            //     userId:this.user.userId,
            //     points: this.totalUsedScore,
            //     coupon: 'xxx',
            //     orderTotal:this.totalPrice - this.totalCut
            // }))
            // .then(response =>{
            //     if(response.data !== 0){
            //         console.error('更新订单失败！');
            //     }
            //     console.log('更新订单失败！')
            // })
            // .catch(error => {
            //     console.error(error);
            // })
        },//自定义过滤器
        sexFilter(value){
            return value==1?'先生':'女士';
        },
        handleUserOrNotSelection(value) {
            this.$nextTick(() => {
                this.userOrNot = value;
                });
        },
        toUserCouponPackage(){
            this.$router.push({path:'/userCouponPackage', query:{showCouponUseBottom: this.showCouponUseBottom, orderTotal:this.totalPrice, businessId:this.businessId}});
        }
    },
    components:{
        PageRollback
    },
}
</script>

<style scoped>
    /************** 总容器 ***************/
.wrapper {
    width: 100%;
    height: 100%;
}

/************* header部分 ***********/
.wrapper header{
    width: 100%;
    height: 12vw;
    background-color: #0097FF;
    color: #fff;
    font-size: 4.8vw;

    position: fixed;
    left: 0;
    top: 0;
    /* 给予高层叠级别 */
    z-index: 1000;

    /* 位置上下左右居中 */
    display: flex;
    justify-content: center;
    align-items: center;
}

/*********** 订单客户信息部分 *************/
.wrapper .order-info{
    /* 不设置高，因为地址可能不止一行，设置了高有可能导致地址折行 */
    width: 100%;
    background-color: #0097EF;
    color: #fff;
    box-sizing: border-box;
    margin-top: 12vw;/* 外边距 */
    padding: 2vw;/* 内边距 */
}
.wrapper .order-info h5{
    font-size: 3vw;
    font-weight: 300;
}
.wrapper .order-info .order-info-address{
    width: 100%;
    display: flex;/* 弹性布局 */
    justify-content: space-between; /* 主轴方向两端对齐，子元素之间间距都相等 */
    align-items: center; /* 侧轴居中对齐 */

    font-weight: 700;
    user-select: none; /* 禁止用户选择元素内的文本内容 */
    cursor: pointer; /*  当鼠标悬停在元素上时，将鼠标指针设置为指示链接的手型 */
    margin: 1vw 0; /* 上下外边距1vw，左右外边距 0 vw */
}
.wrapper .order-info .order-info-address p{
    width: 90%;
    font-size: 5vw;
}
.wrapper .order-info .order-info-address i{
    /* 右箭头 */
    font-size: 6vw;
}
.wrapper .order-info p{
    font-size: 3vw;
}

/*********** 订单商家信息部分 *************/
.wrapper h3{
    box-sizing: border-box;
    padding: 3vw;
    font-size: 4vw;
    color: #666;
    border-bottom: solid 1px #DDD;/* 底部边框设计，实线灰色 */
}

/************ 订单明细部分 **************/
.wrapper .order-detailed{
    width: 100%;
}
.wrapper .order-detailed li{
    width: 100%;/* 高宽 */
    height: 16vw;

    box-sizing: border-box;/* 大小 */
    padding: 3vw;

    display: flex;/* 位置 */
    justify-content: space-between;
    align-items: center;

    color: #666;/* 颜色 */

}
.wrapper .order-detailed li .order-detailed-left{
    display: flex;
    align-items: center;
}
.wrapper .order-detailed li .order-detailed-left img{
    width: 10vw;
    height: 10vw;
}
.wrapper .order-detailed li .order-detailed-left p{
    font-size: 3.5vw;
}
.wrapper .order-detailed li p{
    font-size: 3.5vw;
    margin-left: 3vw; /* 左外边距 */
}
.wrapper .order-deliveryfree{
    width: 100%;
    height: 16vw;

    box-sizing: border-box;
    padding: 3vw;

    display: flex;
    justify-content: space-between;/* 两端对齐，子元素之间间距都相等*/
    align-items: center;

    color: #666;

    font-size: 3.5vw;
}
/***********订单优惠部分**********/
.discount{
    width: 100%;/* 高宽 */
    padding-bottom: 14vw;
}
.discount .discount-member{
    width: 100%;/* 高宽 */
    height: 16vw;

    box-sizing: border-box;/* 大小 */
    padding: 3vw;

    display: flex;/* 位置 */
    justify-content: space-between;
    align-items: center;

    color: #666;/* 颜色 */
}
.discount .discount-member .discount-member-left{
    display: flex;
    align-items: center;
}
.discount .discount-member .discount-member-left i{
    padding: 1vw;
    background-color: #FF4500;
    color: #fff;
    border-radius: 1vw;
}
.discount .discount-member .discount-member-left p{
    margin-left: 2vw;
}
.discount .discount-member-right {
    margin-right: 2vw;
}
.discount .discount-member-right p{
    color: #DC143C;
}

.discount .discount-score{
    width: 100%;/* 高宽 */
    height: 16vw;

    box-sizing: border-box;/* 大小 */
    padding: 3vw;

    display: flex;/* 位置 */
    justify-content: space-between;
    align-items: center;

    color: #666;/* 颜色 */
}
.discount .discount-score .discount-score-left{
    display: flex;
    align-items: center;
}
.discount .discount-score .discount-score-left .discount-score-left-icon{
    padding:0.5vw 1.2vw ;
    background-color: #FF4500;
    color: #fff;
    border-radius: 1vw;
}
.discount .discount-score .discount-score-left p{
    margin-left: 2vw;
}
.discount .discount-score-right {
    box-sizing: border-box;/* 大小 */
    padding: 2vw;

    display: flex;/* 位置 */
    justify-content: space-between;
    align-items: center;
}
.discount .discount-score-right .discount-score-right-userOrNot{

}
.discount .discount-score-right p{
    color: #DC143C;
    margin-left: 3vw;
}

.discount .discount-coupon-package{
    width: 100%;/* 高宽 */
    height: 16vw;

    box-sizing: border-box;/* 大小 */
    padding: 3vw;

    display: flex;/* 位置 */
    justify-content: space-between;
    align-items: center;

    color: #666;/* 颜色 */
}
.discount .discount-coupon-package .discount-coupon-package-left{
    display: flex;
    align-items: center;
}
.discount .discount-coupon-package .discount-coupon-package-left p:first-child{
    padding:0.5vw 1.2vw ;
    background-color: #FF4500;
    color: #fff;
    border-radius: 1vw;
}
.discount .discount-coupon-package .discount-coupon-package-left p:last-child{
    margin-left: 2vw;
}
.discount .discount-coupon-package-right {
    box-sizing: border-box;/* 大小 */
    padding: 2vw;

    display: flex;/* 位置 */
    justify-content: space-between;
    align-items: center;
}
.discount .discount-coupon-package-right .discount-coupon-package-right-used{
    color: #DC143C;
    margin-left: 3vw;
}
 .discount-coupon-package-right .discount-coupon-package-right-unused {
    display: flex;/* 位置 */
    justify-content: space-between;
    align-items: center;
}
.discount-coupon-package-right .discount-coupon-package-right-unused p{
    padding:0.5vw 1.2vw ;
    background-color: #FF4500;
    color: #fff;
    border-radius: 1vw;
}
.discount-coupon-package-right .discount-coupon-package-right-unused i{
    font-size: 6vw;
    margin-left: 3vw;
}
/************ 订单合计部分 *************/
.total {
    width: 100%;
    height: 14vw;

    position: fixed;
    left: 0;
    bottom: 0;

    display: flex;
}
.total .total-left{
    flex: 2; /*占据页面 2/3 */

    display: flex;
    flex-direction: column; /* 设置为垂直方向的列布局 */
    justify-content: center;
    align-items: center;

    color:  #fff;
    background-color: #505051;

    user-select: none; /* 禁止用户选择元素内的文本内容 */
}
.total .total-left p:first-child{
    font-size:  4.5vw;
    font-weight: 700; 
}
.total .total-left p:last-child{

}
.total .total-right{
    flex: 1; /*占据页面 1/3 */

    display: flex;
    justify-content: center;
    align-items: center;

    color:  #fff;
    background-color: #38CA73;

    font-size:  4.5vw;
    font-weight: 700;

    user-select: none; /* 禁止用户选择元素内的文本内容 */
    cursor: pointer; /*  当鼠标悬停在元素上时，将鼠标指针设置为指示链接的手型 */
}

</style>